<?php
/**
 * Created by PhpStorm.
 * User: man0sions
 * Date: 16/8/25
 * Time: 下午7:48
 */

namespace src\commands;


use src\Factory\FormatStrategy\SohuFormatStrategy;
use src\Factory\SpiderDataFactory\SohuSpiderData;
use src\base\AppException;
use src\base\Spider;
use src\models\Playlist;
use src\models\Video;
use src\utils\request\HttpRequest;
use src\utils\request\RandUseragentFetch;
use src\utils\Utils;

/**
 * Class Sohu
 * 抓取sohu的类,继承spider
 * 实现playlist抓取,并保存
 * 实现videos抓取,并保存
 *
 * @package src\commands
 */
class Sohu extends Spider
{
    private $rs_video = 4;
    private $site = 1;
    private $spider_data;

    function __destruct()
    {
//        var_dump(__CLASS__."==>__destruct\n");
    }

    function __construct()
    {
        $this->spider_data = new SohuSpiderData(new SohuFormatStrategy());
    }

    /**
     * @param $url
     * @param $firstcategoryid
     * @return bool
     * @throws AppException
     */
    function doSpider($url, $firstcategoryid)
    {

        $request = new HttpRequest($url,new RandUseragentFetch());
        $res = json_decode($request->fetch());
        if($res->status!=200)
        {
            echo "==>fetch error:{$res}\n";
            return false;
        }

        if(count($res->data->videos)==0)
        {
            echo "==>data empty\n";
            return false;
        }

        foreach ($res->data->videos as $key => $val) {
            $this->savePlaylist($val, $firstcategoryid);
        }
    }

    /**
     * 把sohu api返回的数据视频据列表封住成ThirdPlaylist 对象 然后在对ThirdPlaylist 进行 save(insert / update)
     *
     * @param $item
     * @param $firstcategoryid
     * @throws AppException
     */
    private function savePlaylist($item, $firstcategoryid)
    {
        $item->firstcategoryid = $firstcategoryid;
        $item->creator = 'VideoSpider';
        $item->rs_video =$this->rs_video;
        $item->site =$this->site;
        $playlist = Playlist::model()->fields(['*'])
            ->where(['thirdaid' => $item->aid])
            ->find();

        if(!$playlist->getAttributes())
            $playlist = new Playlist($new_record=true);
        foreach($this->spider_data->createPlaylistData($item) as $key=>$value)
            $playlist->$key = $value;

        try{
            if(!$playlist->save())
            {
                var_dump($playlist->getErrors());
            }
            $count = 0;
            $count = $this->saveVideos($playlist);
            echo "==> 抓取playlist {$playlist->name} : 共 {$count} 集  {$playlist->id} \n";
        }catch(\Exception $e){
            throw new AppException("salve playlist error:{$e}");
        }


    }

    /**
     * 把sohu api返回的剧集信息封住成 ThirdVideo 对象,然后对 ThirdVideo 进行 save(insert / update)
     * @param $playlist
     * @return int
     */
    private function saveVideos($playlist)
    {
        $api = "http://api.tv.sohu.com/v4/album/videos/{$playlist->thirdaid}.json?_from=h5&api_key=695fe827ffeb7d74260a813025970bd5&page_size=1000";
        $request = new HttpRequest($api,new RandUseragentFetch());
        $res = json_decode($request->fetch());
        $count = 0;
        foreach($res->data->videos as $key=>$item)
        {

            $item->thirdplaylistid = $playlist->id;
            $item->rs_video = $this->rs_video;
            $item->site =$this->site;
            $item->url = '';//$this->config['m3u8_parse'].Utils::encrypt($item->url_html5,'m3u8_parse');


            $video = Video::model()->fields(['*'])
                ->where(['thirdvid'=>$item->vid])
                ->find();
            if(!$video->getAttributes())
                $video = new Video($new_record=true);

            foreach($this->spider_data->createVideoData($item) as $name=>$value)
                $video->$name = $value;


            if($video->save())
            {
                $count++;
                echo "==> 抓取videos {$playlist->name} : 第 { $video->videoseq } 集\n";
            }
            else
            {
                var_dump($video->getErrors());
            }

        }
        return $count;
    }
}